package com.example.smartcity.Service.Impl;

import com.example.smartcity.Mappers.CountMapper;
import com.example.smartcity.Mappers.SuiShouPaiMapper;
import com.example.smartcity.Mappers.UserMapper;
import com.example.smartcity.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;

@Service
public class FileUploadService {

    private final String uploadDir = "F:\\smartcity_picture\\";

    public void saveImage(MultipartFile file,String uid) throws IOException, SQLException {

        System.out.println("File uploaded: " + file.getOriginalFilename());
        if (file != null) {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            int dotIndex = fileName.lastIndexOf(".");
            String mediatype = fileName.substring(dotIndex);
            String uid2 = uid;
            int uuid = Integer.parseInt(uid2);


            System.out.println("Current filename " + file.getOriginalFilename());



            SqlSession sqlSession1 = MybatisUtils.getSqlSession();
            UserMapper userMapper = sqlSession1.getMapper(UserMapper.class);
            System.out.println("1");
            userMapper.updateUserAvatarByUid(uuid,"/images/"+uuid+file.getOriginalFilename());
            System.out.println('2');
            sqlSession1.commit();
            sqlSession1.close();

            // 获取文件类型
            String contentType = file.getContentType();


            // 获取文件大小
            byte[] bytes = file.getBytes();
            System.out.println("Current filename " + file.getOriginalFilename());
            Path path = Paths.get(uploadDir +uuid+file.getOriginalFilename() );
            Files.write(path, bytes);
            System.out.println("File uploaded successfully!");


        }
    }
    public void savesuishoupaiimg(List<byte[]> files,List<String> names,String content,String title,String authorid)throws IOException, SQLException{
        String namelist = "";
        for(int i=0;i<files.size();i++){
            byte[] file = files.get(i);
            String name = names.get(i);
            Path path = Paths.get(uploadDir +name );
            Files.write(path, file);
            System.out.println("已将图片"+name+"上传到服务器");
        }
        for(String name:names){
            namelist=namelist+"/images/"+name+",";
        }
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        SuiShouPaiMapper suiShouPaiMapper = sqlSession.getMapper(SuiShouPaiMapper.class);
        suiShouPaiMapper.SaveSSP(content,title,namelist,authorid);
        sqlSession.commit();
        sqlSession.close();
        System.out.println("已创建新的随手拍");
    }


}